package com.csii.ams.controller;

import com.csii.adhoc.annotation.OperationLog;
import com.csii.ams.ArchAbn;
import com.csii.ams.ArchDef;

import com.csii.ams.service.ArchAbnService;
import com.csii.ams.service.ArchDefService;
import com.csii.result.APIResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: 档案定义
 * @author: panChuanJiang
 * @create: 2021-03-18 09:07
 */
@Controller
@Slf4j
@RequestMapping("/**/ams/archDef")
public class ArchDefController {
    @Resource
    private ArchDefService archDefService;
    @Resource
    private ArchAbnService archAbnService;
    @Value("${poc.ams.filehome}")
    private String filehome;

    /**
     * 上传补录文件
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadFile")
    @ResponseBody
    public APIResult<String> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("archCd") String archCd,
                             @RequestParam("idCard") String idCard) throws IOException {
        ArchDef archDef = new ArchDef();
        archDef.setArchCd(archCd);
        List<ArchDef> archDefs = archDefService.queryListArchDef(archDef);
        String dir = filehome;
        if (archDefs != null && archDefs.size() == 1) {
            dir = dir + File.separator + archDefs.get(0).getArchCd();
        } else {
            throw new RuntimeException("archCd 输入不合法");
        }

        if (file.isEmpty()) {
            return APIResult.failResult("failed","文件为空");
        }
        //2.获取文件名称
        String fileName = file.getOriginalFilename();
        log.info("uploadFileName:" + fileName);
        String[] split = fileName.split("\\.");
        String type = split[split.length - 1];
        //3.定义文件夹路径
        File fileDir = new File(dir);
        if (!fileDir.exists()) {
            //创建文件夹
            fileDir.mkdirs();
        }
        File[] files = fileDir.listFiles();
        for (File f :files) {
           if (f.getName().contains(idCard)){
               f.delete();
           }
        }
        //4.实现文件上传
        File file1 = new File(dir + File.separator + idCard + "." + type);
        file.transferTo(file1);
        ArchAbn archAbn = new ArchAbn();
        archAbn.setAbnStat("00");
        archAbn.setCustNo(idCard);
        archAbn.setArchCd(archDefs.get(0).getArchCd());
        archAbnService.updateArchAbn(archAbn);
        return APIResult.successResult("success");
    }

    @RequestMapping(value = "/downloadFile")
    //@OperationLog("查看档案详情")
    public void downloadFile(@RequestParam("archCd") String archCd, @RequestParam("idCard") String idCard,
                             HttpServletResponse response) throws IOException {
        ArchDef archDef = new ArchDef();
        archDef.setArchCd(archCd);
        List<ArchDef> archDefs = archDefService.queryListArchDef(archDef);
        String path = filehome;
        if (archDefs != null && archDefs.size() == 1) {
            path = path + File.separator + archDefs.get(0).getArchCd();
        } else {
            throw new RuntimeException("archCd 输入不合法");
        }
        File dir = new File(path);
        File[] files = dir.listFiles();
        if (files == null) {
            return;
        }
        StringBuilder fileName = new StringBuilder();
        Arrays.stream(files).forEach(x -> {
            if (x.getName().contains(idCard)) {
                fileName.append(x.getName());
            }
        });
        File f = new File(path + File.separator + fileName);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        try (BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
             OutputStream out = response.getOutputStream()) {
            byte[] buf = new byte[1024];
            int len = 0;
            response.reset(); // 非常重要
            //if (1 == 1) { // 在线打开方式
            URL u = new URL("file:///" + path);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
            /*} else { // 纯下载方式
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
            }*/
            while ((len = br.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
    }


    @RequestMapping("queryArchByBusiCdAndIdCard")
    @ResponseBody
    @OperationLog("查询个人档案列表")
    public APIResult<List<ArchDef>>  queryArchByBusiCdAndIdCard(@RequestBody Map<String,String> map) {
        List<ArchDef> archDefs = archDefService.queryArchDefs(map, filehome);
        String archNm = map.get("archNm");
        if (!StringUtils.isEmpty(archNm)){
            archDefs = archDefs.stream().filter(x -> x.getArchNm().equals(archNm)).collect(Collectors.toList());
        }
        return APIResult.successResult(archDefs);
    }

    @RequestMapping("addArchDef")
    @OperationLog("新增档案定义")
    @ResponseBody
    public APIResult<?> addArchDef(@RequestBody ArchDef archDef) {
        archDef.setArchStat("00");
        if (StringUtils.isEmpty(archDef.getArchCd())) {
            archDefService.insertArchDef(archDef);
        } else {
            archDefService.updateArchDef(archDef);
        }
        return APIResult.successResult(null);
    }

    @RequestMapping("updateArchDef")
    @OperationLog("更新档案定义")
    @ResponseBody
    public APIResult<?> updateArchDef(@RequestBody ArchDef archDef) {
        archDefService.updateArchDef(archDef);
        return APIResult.successResult(null);
    }

    @RequestMapping("deleteArchDef")
    @OperationLog("删除档案定义")
    @ResponseBody
    public APIResult<?> deleteArchDef(@RequestBody ArchDef archDef) {
        archDefService.deleteArchDef(archDef.getArchCd());
        return APIResult.successResult(null);
    }

    @RequestMapping("queryListArchDef")
    @OperationLog("查询档案定义")
    @ResponseBody
    public APIResult<List<ArchDef>> queryListArchDef(@RequestBody(required = false) ArchDef archDef) {
        return APIResult.successResult(archDefService.queryListArchDef(archDef));
    }
}
